<?php

/**
 * Author: 孙武 QQ:1228746736
 * Date: 2018/2/17
 * Time: 13:14
 */

namespace app\home\def;

use app\home\model\Resource;
use app\home\model\ResourceCategory;

class Search
{

    private $resModel;
    private $catModel;
    /*
     * string
     */
    private $keyword = '';
    /*
     * desc/asc
     */
    private $order = '';
    /*
     * ['guid','guid']
     */
    private $cats = [];
    /*
     * [
          'start' => $time,
           'end' => $nextMonthTime
       ];
     */
    private $time = [];


    public function __construct($search)
    {

        /*
         * $search
         * array(4) {
         *  ["keyword"]=> string(1) "s"
         *  ["cats"]=> array(0) { }
         *  ["order"]=> array(1) { ["order"]=> string(4) "desc" }
         *  ["time"]=> array(0) { } }
         */
        $this->resModel = new Resource();
        $this->catModel = new ResourceCategory();
        $this->keyword = $search['keyword'];
        $this->getsGuidByNames($search['cats']);

        if (empty($search['time'])) {
            $this->time = $this->getYearMinAndMaxTimestamp('0', true);
        } else {
            $this->time = $this->getYearMinAndMaxTimestamp($search['time']['year']);
        }
        $this->order = $search['order']['order'];
    }

    private function getsGuidByNames($catsName)
    {
        if (!is_array($catsName)) return;
        foreach ($catsName as $v) {
            $res = $this->catModel->where("Name", $v)->value('PK_ResourceCategoryGuid');
            $this->cats[] = $res;
        }
        return;
    }

    /**
     * 搜索构建数据
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function data()
    {

        if (count($this->cats) > 0) { //存在分类
            return  $this->resModel->
            where("Title|Desc", 'like', "%$this->keyword%")->
            where('FK_ResourceCategoryGuid', 'in', $this->cats)->
            where('UpdateTime', ['>', $this->time['start']], ['<', $this->time['end']])->
            order("UpdateTime $this->order")->
            select();
        } else {//不存在分类
            return $this->resModel->
            where("Title|Desc", 'like', "%$this->keyword%")->
            where('UpdateTime', ['>', $this->time['start']], ['<', $this->time['end']])->
            order("UpdateTime $this->order")->
            select();
        }
    }


    /**
     * 获取指定年份的起始时间戳和终止时间戳
     * @param $time string  $time='2017';
     */
    private function getYearMinAndMaxTimestamp($year, $all = false)
    {

        $nowYear = $year . "-01-01";
        $nYeay = $year + 1;
        $nextYear = $nYeay . "-01-01";
        if ($all === true) {
            return [
                'start' => 0,
                'end' => 2147480000
            ];
        } else {

            return [
                'start' => strtotime($nowYear),
                'end' =>  strtotime($nextYear)
            ];
        }

    }

}